<template>
  <div>
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body :before-close="cancel">
      <el-form ref="partyinfoRef" label-position="right" :model="form" :rules="rules" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="当事人名称" prop="partyId">
              <el-select
                v-model="form.partyId"
                filterable
                remote
                clearable
                reserve-keyword
                placeholder="请输入当事人名称"
                :remote-method="handlepartySearch"
                :loading="partyLoading"
                @change="handlepartyChange">
                <el-option v-for="item in partyOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="类型" prop="type">
              <el-radio-group v-model="form.type" @change="handleTypeChange">
                <el-radio v-for="item in photo_type" :key="item.value" :label="item.label" :value="item.value">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.type == '3'" :span="5">
            <el-form-item label-width="0" prop="typeOther">
              <el-input v-model="form.typeOther" placeholder="请输入其他类型" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收集时间" prop="collectionTime">
              <el-date-picker
                clearable
                v-model="form.collectionTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择收集时间"
                style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收集方式" prop="collectionMethod">
              <el-radio-group v-model="form.collectionMethod" @change="handleCollectionChange">
                <el-radio v-for="item in collection_method" :key="item.value" :label="item.label" :value="item.value">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.collectionMethod == '2'" :span="5" :pull="2">
            <el-form-item label-width="0" prop="collectionMethodOther">
              <el-input v-model="form.collectionMethodOther" placeholder="请输入其他收集方式" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="收集地点" :rules="rules.collectionLocation" prop="collectionLocation">
              <!-- <locationSelect v-model="form.addressObj" /> -->
              <el-input v-model="form.collectionLocation" placeholder="请输入收集地点" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="收集人员姓名" prop="inspectorId1">
              <el-select
                v-model="form.inspectorId1"
                filterable
                clearable
                placeholder="请输入收集人员"
                @change="handlepartyChange1">
                <el-option v-for="item in inspectorOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="证件号码" prop="inspectorCertNo1">
              <el-input v-model="form.inspectorCertNo1" placeholder="请输入证件号码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收集人员姓名" prop="inspectorId2">
              <el-select
                v-model="form.inspectorId2"
                filterable
                clearable
                placeholder="请输入收集人员"
                @change="handlepartyChange2">
                <el-option v-for="item in inspectorOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="证件号码" prop="inspectorCertNo2">
              <el-input v-model="form.inspectorCertNo2" placeholder="请输入证件号码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="证明内容" prop="certificationContent">
              <SmartTextInput
                v-model="form.certificationContent"
                type="textarea"
                :rows="4"
                placeholder="请输入证明内容，输入关键词后按Tab键快速补全"
                :min-length="2"
                :max-suggestions="5"
                contentType="100" />
            </el-form-item>
          </el-col>
          <el-form-item label="上传照片" :rules="rules.photos" prop="photos">
            <imageUpload v-model="form.photos" />
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">提 交</el-button>
          <el-button :loading="preViewLoading" @click="handlePreview">预览</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, getCurrentInstance, computed, watch } from 'vue'
import {
  getPhotoregistration,
  addPhotoregistration,
  updatePhotoregistration,
  previewPhotoregistrationPdf,
} from '@/api/photoRegistration/index'
import { getUserEnforcementNo } from '@/api/system/user.js'
import { listPartyinfo } from '@/api/partyinfo/index'
import locationSelect from '@/components/locationSelect/index.vue'
import SmartTextInput from '@/components/SmartTextInput/index.vue'
import { ElMessage } from 'element-plus'

const { proxy } = getCurrentInstance()
const { photo_type, collection_method } = proxy.useDict('photo_type', 'collection_method')

const props = defineProps({
  id: {
    type: [String, Number],
    default: undefined,
  },
  value: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '',
  },
})
const emit = defineEmits(['update:value', 'getList'])
const open = computed({
  get: () => props.value,
  set: (val: boolean) => emit('update:value', val),
})

const partyinfoRef = ref<any>()
const form = ref<any>({
  // addressObj: {
  //   streetOfPhotoLocation: undefined,
  //   photoLocation: undefined,
  // },
})
// 自定义校验器：检查拍摄地点是否完整
const validateLocation = (rule: any, value: any, callback: any) => {
  if (!value || !value.streetOfPhotoLocation || !value.photoLocation) {
    callback(new Error('请选择地址'))
  } else {
    callback()
  }
}
const rules = {
  partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
  addressObj: [{ required: true, validator: validateLocation, trigger: ['blur', 'change'] }],
  collectionLocation: [{ required: true, message: '收集地点不能为空', trigger: ['blur', 'change'] }],
  type: [{ required: true, message: '类型不能为空', trigger: ['blur', 'change'] }],
  typeOther: [{ required: true, message: '类型其他不能为空', trigger: ['blur', 'change'] }],
  collectionTime: [{ required: true, message: '收集时间不能为空', trigger: ['blur', 'change'] }],
  collectionMethod: [{ required: true, message: '收集方式不能为空', trigger: ['blur', 'change'] }],
  collectionMethodOther: [{ required: true, message: '收集方式其他不能为空', trigger: ['blur', 'change'] }],
  inspectorId1: [{ required: true, message: '收集人员姓名不能为空', trigger: ['blur', 'change'] }],
  inspectorCertNo1: [{ required: true, message: '收集人员证件号码不能为空', trigger: ['blur', 'change'] }],
  inspectorId2: [{ required: true, message: '收集人员姓名不能为空', trigger: ['blur', 'change'] }],
  inspectorCertNo2: [{ required: true, message: '收集人员证件号码不能为空', trigger: ['blur', 'change'] }],
  certificationContent: [{ required: true, message: '证明内容不能为空', trigger: ['blur', 'change'] }],
  photos: [{ required: true, message: '请上传照片', trigger: ['blur', 'change'] }],
}

watch(
  () => props.id,
  newVal => {
    if (newVal) {
      getInfo()
    }
  },
  { immediate: true }
)

function getInfo() {
  getPhotoregistration(props.id).then(response => {
    form.value = response.data
    form.value.inspectorId1 = String(form.value.inspectorId1)
    form.value.inspectorId2 = String(form.value.inspectorId2)
    // form.value.addressObj = {
    //   photoLocation: form.value.streetOfLocation,
    //   streetOfPhotoLocation: form.value.collectionLocation,
    // }
  })
}

// 表单重置
function reset() {
  for (const key in form.value) {
    form.value[key] = undefined
  }
  proxy.resetForm('partyinfoRef')
  console.log(form.value)
}
// 取消按钮
function cancel() {
  reset()
  nextTick(() => {
    open.value = false
  })
}
// 当事人名称下拉
const partyLoading = ref(false)
const partyOptions = ref<Array<any>>([])
const handlepartySearch = async (query: string) => {
  partyLoading.value = true
  const res: any = await listPartyinfo({
    pageNum: 1,
    pageSize: 9999,
    partyName: query,
  })
  partyLoading.value = false
  partyOptions.value = res.rows.map(item => {
    return { value: String(item.id), label: item.partyName, ...item }
  })
}
handlepartySearch('')
// 选择当事人
const handlepartyChange = (val: string) => {
  form.value.partyName =
    partyOptions.value.find(item => {
      return item.value === val
    })?.label || undefined
}

// 类型选择
const handleTypeChange = (val: string) => {
  if (val !== '3') {
    form.value.typeOther = undefined
  }
}
// 收集方式选择
const handleCollectionChange = (val: string) => {
  if (val !== '2') {
    form.value.collectionMethodOther = undefined
  }
}

const inspectorOptions = ref<Array<any>>([])
const getUserList = async () => {
  const res = await getUserEnforcementNo({})
  if (res.data.length > 0) {
    inspectorOptions.value = res.data.map((item: any) => {
      return { value: item.userId, label: item.name, enforcementNo: item.enforcementNo }
    })
  }
}
getUserList()
const handlepartyChange1 = (val: string) => {
  if (val === form.value.inspectorId2) {
    form.value.inspectorName1 = null
    form.value.inspectorId1 = null
    form.value.inspectorCertNo1 = null
    return
  }
  inspectorOptions.value.forEach(item => {
    if (item.value === val) {
      form.value.inspectorCertNo1 = item.enforcementNo
      form.value.inspectorName1 = item.label
    }
  })
}
const handlepartyChange2 = (val: string) => {
  if (val === form.value.inspectorId1) {
    form.value.inspectorName2 = null
    form.value.inspectorId2 = null
    form.value.inspectorCertNo2 = null
    return
  }
  inspectorOptions.value.forEach(item => {
    if (item.value === val) {
      form.value.inspectorCertNo2 = item.enforcementNo
      form.value.inspectorName2 = item.label
    }
  })
}
const preViewLoading = ref(false)
const handlePreview = () => {
  preViewLoading.value = true
  submitForm(true)
    .then(async params => {
      const res: any = await previewPhotoregistrationPdf(params)
      if (!!res.msg) {
        window.open(res.msg)
      } else {
        ElMessage.warning('预览文件不存在')
      }
      preViewLoading.value = false
    })
    .catch(() => {
      preViewLoading.value = false
    })
}
/** 提交按钮 */
function submitForm(isPreview = false) {
  return new Promise((relove, reject) => {
    proxy.$refs['partyinfoRef'].validate(valid => {
      if (valid) {
        const params = JSON.parse(JSON.stringify(form.value))
        // params.streetOfLocation = form.value.addressObj.photoLocation
        // params.collectionLocation = form.value.addressObj.streetOfPhotoLocation
        if (isPreview === true) {
          relove(params)
          return
        }
        if (params.id != null) {
          updatePhotoregistration(params).then(response => {
            proxy.$modal.msgSuccess('修改成功')
            reset()
            nextTick(() => {
              open.value = false
              emit('getList')
            })
          })
        } else {
          addPhotoregistration(params).then(response => {
            proxy.$modal.msgSuccess('新增成功')
            reset()
            nextTick(() => {
              open.value = false
              emit('getList', params)
            })
          })
        }
      } else {
        reject()
      }
    })
  })
}
</script>

<style scoped></style>
